package nuc.ss.wl.controller;

import com.google.gson.Gson;
import nuc.ss.wl.entity.Course;
import nuc.ss.wl.service.CourseService;
import nuc.ss.wl.service.impl.CourseServiceImpl;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class CourseServlet extends BaseServlet {

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int cno = Integer.parseInt(request.getParameter("cno"));
        String cname = request.getParameter("cname");
        int cpno = Integer.parseInt(request.getParameter("cpno"));
        int ccredit = Integer.parseInt(request.getParameter("ccredit"));
        Course course = new Course();
        course.setCno(cno);
        course.setCname(cname);
        course.setCpno(cpno);
        course.setCcredit(ccredit);

        CourseService courseService = new CourseServiceImpl();
        int i = courseService.add(course);
        if (i > 0) {
            response.sendRedirect(request.getContextPath() + "/courseServlet?action=findAll");
        } else {
            /*request.setAttribute("error","添加课程失败");
            request.getRequestDispatcher("").forward(request, response);*/
        }
    }

    protected void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        int cno = Integer.parseInt(request.getParameter("cno"));
        CourseService courseService = new CourseServiceImpl();
        int delete = courseService.delete(cno);
        if (delete > 0) {
            response.sendRedirect(request.getContextPath() + "/courseServlet?action=findAll");
        } else {
            System.out.println("有学生选课");
        }
    }

    /**
     * 更新数据
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        int cno = Integer.parseInt(request.getParameter("cno"));
        String cname = request.getParameter("cname");
        int cpno = Integer.parseInt(request.getParameter("cpno"));
        int ccredit = Integer.parseInt(request.getParameter("ccredit"));
        // 对象处理
        Course course = new Course();
        course.setCno(cno);
        course.setCname(cname);
        course.setCpno(cpno);
        course.setCcredit(ccredit);
        // 调用业务层(完成添加)进行处理
        CourseService courseService = new CourseServiceImpl();
        int i = courseService.update(course);
        // 根据结果进行页面跳转
        if (i > 0) {
            response.sendRedirect(request.getContextPath() + "/courseServlet?action=findAll");
        } else {
           /* request.setAttribute("error","更新课程失败");
            request.getRequestDispatcher("").forward(request, response);*/
            System.out.println("有学生选课，暂不支持更改");
        }
    }

    protected void findAll(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
        CourseService courseService = new CourseServiceImpl();
        List<Course> courseList = courseService.findAll();
        request.setAttribute("courseList", courseList);
        request.getRequestDispatcher("/pages/manager/course_manager.jsp").forward(request, response);
    }

    protected void findCnoAndCname(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
        CourseService courseService = new CourseServiceImpl();
        List<Course> courseList = courseService.findAll();
        response.setContentType("text/html; charset=utf-8");
        System.out.println(courseList);
        response.getWriter().println(new Gson().toJson(courseList));
    }

    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void teacherFindById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int cno = Integer.parseInt(request.getParameter("cno"));
        CourseService courseService = new CourseServiceImpl();
        Course course = courseService.findById(cno);
        request.setAttribute("course", course);
        request.getRequestDispatcher("/pages/manager/course_edit.jsp").forward(request, response);
    }


    public void exportXLS(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用业务层完成查询操作
        CourseService courseService = new CourseServiceImpl();
        List<Course> courseList = courseService.findAll();
        //返回json字符串
        createExcel(courseList,response);
    }
    /**
     * 创建Excel
     * @param courseList
     *            数据
     */
    private static void createExcel(List<Course> courseList,HttpServletResponse response) {
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表
        HSSFSheet sheet = workbook.createSheet("课程信息表1");
        CellRangeAddress region = new CellRangeAddress(0, // first row
                0, // last row
                0, // first column
                3 // last column
        );
        sheet.addMergedRegion(region);
        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("课程详细信息");
        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        headCell.setCellStyle(cellStyle);


        // 添加表头行
        hssfRow = sheet.createRow(1);
        // 添加表头内容
        headCell = hssfRow.createCell(0);
        headCell.setCellValue("课程号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("课程名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(2);
        headCell.setCellValue("先修课程号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("学分");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < courseList.size(); i++) {
            hssfRow = sheet.createRow((int) i + 2);
            Course course= courseList.get(i);

            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(course.getCno());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(course.getCname());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(2);
            cell.setCellValue(course.getCpno());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(3);
            cell.setCellValue(course.getCcredit());
            cell.setCellStyle(cellStyle);

        }

        // 保存Excel文件
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment; fileName=course.xls" );//附件形式下载，文件名叫duty.xls
            //OutputStream outputStream = new FileOutputStream("D:/course1.xls");  保存到了服务器端
            OutputStream outputStream = response.getOutputStream();//保存到客户端
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
